import appConfig from './config.js';
import axios from 'axios';
import { useMainStore } from '../store';
import router from '../router';

import {
	ElMessage
} from 'element-plus';

// axios配置
axios.defaults.baseURL = appConfig.domain;
const mainStore = useMainStore();

// 请求拦截器
axios.interceptors.request.use(
	config => {
		// 自定义请求头
		if (mainStore.user) {
			config.headers.Authorization = 'bearer ' + mainStore.user.token;
		}
		return config;
	}, error => {
		return Promise.reject(error);
	}
);

//  响应拦截器
axios.interceptors.response.use(
	response => {
		if (response.data.code != 200) {
			ElMessage.error(response.data.msg);
		}

		return Promise.resolve(response);
	}, error => {
		if (error.response.status == 500) {
			ElMessage.error(error.response.statusText);
		} else if (error.response.status == 420) {
			router.push('/user/login')
		} else {
			ElMessage.error(error.response.data.message);
		}

		return Promise.reject(error);
	}
)

export default {
	domain: appConfig.domain,
	post(url, params = {}, Headers = {}) {
		return new Promise((resolve, reject) => {
			axios.post(url, params, Headers)
				.then(res => {
					return resolve(res.data);
				}).catch(err => {
					// console.log(err.response)
				})
		});
	},
	get(url, data = {}, Headers = {}) {
		return new Promise((resolve, reject) => {
			let datas = {};
			datas.params = data;
			axios.get(url, datas, Headers).then(res => {
				return resolve(res.data);
			}).catch(err => {
				// console.log(err.response)
			})
		});
	}
}
